﻿using UnityEngine;
using System.Collections;
using view.homepage;
using System.IO;
using facepp.detection;
using System;

public class View_homePage : MonoBehaviour {
    public UIButton btn_photo;


    public UITexture img_camera;

    public UITexture Img_Tie;


	//关键点 
	public UITexture left_eye_pupil;
	public UITexture right_eye_pupil;
	// // //

    internal float screenHeight;
    internal float screenWidth;
    internal float scaY ;
    internal float scaX;

    internal float webCameraWidth = 1080;
    internal float webCameraHeight = 607;

    private Model _model = new Model();
	// Use this for initialization
	void Start () {

        screenHeight = Screen.height;
        screenWidth = Screen.width;
        scaX= screenWidth / 1080;
        scaY=screenHeight / 1920;
        new Controller_btnphoto(this,_model);
        new Controller_imgCamera(this);
        new Controller_facePp(this,_model);
        new Controller_TieTu(this, _model);

        
        _model.changeAnalyzeImg += new EventHandler(onChnageTestData);
	}
    private void onChnageTestData(object sender, EventArgs e)
    {
       // Debug.Log(_model.testData);
    }
	// Update is called once per frame
	void Update () {
	
	}
}



namespace view.homepage
{
    public class Model
    {
       
        public event EventHandler changeAnalyzeImg;

        private byte[] _analyzeImgByt = null;//私有的
        public byte[]  analyzeImgByt
        {
            //只读
            get {
                return _analyzeImgByt;//返回私有的_analyzeImgByt
            }
            //数据可更改
            set {

                //判断私有的_analyzeImgByt 是否=传进来的value,true直接返回，不执行下面的代码
                if (_analyzeImgByt == value)
                {
                    return;
                }
                //如果不=，赋值传进来的value 给 _analyzeImgByt， 并开始执行剩下的代码
                _analyzeImgByt = value;

                //传递事件，任何代码块注册了该事件的地方都会收到消息，类式 大家都订阅了这个报纸，报纸有新闻时会发送到您的邮箱或者其他什么的，然后您开始阅读相关内容
                if (changeAnalyzeImg != null)
                {
                    changeAnalyzeImg(this, EventArgs.Empty);
                }
            }

        }
        public event EventHandler AnalyzeiFace;
        private FaceLandMarkData _lanDmarkData;
        public FaceLandMarkData lanDmarkData
        {
            get { return _lanDmarkData; }
            set {
                if (_lanDmarkData == value)
                {
                    return;
                }
                _lanDmarkData = value;
                if (AnalyzeiFace != null)
                {
                    AnalyzeiFace(this, EventArgs.Empty);
                }
            }
        }


        public Model()
        {

        }
    }


    #region 拍照按钮

    /// <summary>
    /// 拍照按钮
    /// </summary>
    public class Controller_btnphoto
    {
        private View_homePage _ui;
        private Model _model;
        public Controller_btnphoto(View_homePage ui,Model model)
        {
            _ui = ui;
            _model = model;
            UIEventListener.Get(_ui.btn_photo.gameObject).onClick = onBtnPhoto;

        }
        private void onBtnPhoto(GameObject btn)
        {
            Debug.Log(btn.name);
            Debug.Log("点击了拍照按钮，实现一些东西在这函数里");
            _ui.StartCoroutine(getTexture2d());
        }
        
        IEnumerator getTexture2d()
        {
           
            yield return new WaitForEndOfFrame();
            Texture2D t = new Texture2D(_ui.img_camera.width, (int)(Screen.height * .5f));//要保存图片的大小
            //截取的区域
            t.ReadPixels(new Rect(0, Screen.height * .5f, _ui.img_camera.width, Screen.height * .5f), 0, 0, false);
            t.Apply();
            //把图片数据转换为byte数组
            byte[] byt = t.EncodeToJPG();
            _model.analyzeImgByt = byt;
            //然后保存为图片
            File.WriteAllBytes(Application.dataPath + "/shexiang/" + Time.time + ".jpg", byt);
            WWW www = new WWW("file://" + Application.dataPath + "/shexiang/" + Time.time + ".jpg");
             _ui.Img_Tie.gameObject.SetActive(true);
            _ui.Img_Tie.mainTexture = www.texture;
        }

    } 
    #endregion

    public class Controller_TieTu
    {
        private View_homePage _ui;
        private Model _model;
        public Controller_TieTu(View_homePage ui, Model model)
        {
            _ui = ui;
            _model = model;
            _model.AnalyzeiFace += new EventHandler(OnGetLandmark_data);
			setActiveLandmarkPoint(false);//先隐藏
        }
		private void setActiveLandmarkPoint(bool isShow){
			_ui.left_eye_pupil.gameObject.SetActive(isShow);
			_ui.right_eye_pupil.gameObject.SetActive(isShow);
		}
        private void OnGetLandmark_data(object obj,EventArgs e)
        {
			setActiveLandmarkPoint(true);//显示

			setTheLandMarkPoint(LandMarkType.LEFT_EYE_PUPIL,_ui.left_eye_pupil);//设置左眼
			setTheLandMarkPoint(LandMarkType.RIGHT_EYE_PUPIL,_ui.right_eye_pupil);//设置右眼
		
        }
		private void setTheLandMarkPoint(string type,UITexture tex,Texture texture=null){
			//如果texture不为空，设置皮肤
			if(texture){
				tex.mainTexture=texture;
			}
			Vector2 postionRelative=_model.lanDmarkData.landmark.getP(type).postionRelative;
			var x =postionRelative.x*_ui.screenWidth;
			var y =postionRelative.y*_ui.screenHeight*.5f;
			tex.transform.localPosition =new Vector3(x,y, 0);
		}


    } 
        

    #region 管理摄像头
    public class Controller_imgCamera
    {
        private View_homePage _ui;
        private WebCamTexture cameraTexture;
        string cameraName = "";
        private bool isPlay = false;
        public Controller_imgCamera(View_homePage ui)
        {
            _ui = ui;
            init();
            _ui.StartCoroutine(Startshe());

        }
        private void init()
        {

            _ui.img_camera.width = (int)(_ui.webCameraWidth * _ui.scaX);
            _ui.img_camera.height = (int)(_ui.webCameraHeight * _ui.scaY);
            _ui.img_camera.transform.localPosition = new Vector3(0, _ui.screenHeight*.25f, 0);


            _ui.Img_Tie.width = (int)(_ui.webCameraWidth * _ui.scaX);
            _ui.Img_Tie.height = (int)(_ui.webCameraHeight * _ui.scaY*1.6f);
            _ui.Img_Tie.transform.localPosition = new Vector3(0, _ui.screenHeight * .25f, 0);

           
        }
        IEnumerator Startshe()
        {
            yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
            if (Application.HasUserAuthorization(UserAuthorization.WebCam))
            {
                WebCamDevice[] devices = WebCamTexture.devices;
                cameraName = devices[0].name;
                cameraTexture = new WebCamTexture(cameraName, 1280,720, 15);
                _ui.img_camera.mainTexture = cameraTexture;
                cameraTexture.Play();
                isPlay = true;
            }
        }
    } 
    #endregion

   
    public class Controller_facePp
    {
        private View_homePage _ui;
        private Model _model;
        public Controller_facePp(View_homePage ui,Model model)
        {
            _ui = ui;
            _model = model;


            Facepp_landmark.instance.api_key = "fb328953796a0393f607593db1a545c4";
            Facepp_landmark.instance.api_secret = "gbQtE6UE2TFOp2VH2mAUU9wKLGssuYtx";


            _model.changeAnalyzeImg += new EventHandler(feixiFacePp);
        }
      
        private  void feixiFacePp(object obj,EventArgs e)
        {
            Debug.Log("开始分析: "+_model.analyzeImgByt.Length);
            // FaceDetectData data = Facepp_detect.instance.getFaceDetectData(byt);
            //  Debug.Log(data.faces.Count);
            FaceLandMarkData landmark_data = Facepp_landmark.instance.getLandMarkDataFromDetect(_model.analyzeImgByt);
            _model.lanDmarkData = landmark_data;
          
            // Debug.Log(landmark_data.landmark.keyPoints.Count);
            // Debug.Log(landmark_data.landmark.keyPoints[0].name + ":" + landmark_data.landmark.keyPoints[0].relative.x);
            //   Debug.Log(landmark_data.landmark.getP(LandMarkType.LEFT_EYE_PUPIL).x);
           //_ui.tex.transform.localPosition = new Vector3(landmark_data.landmark.getP(LandMarkType.LEFT_EYE_PUPIL).relative.x, landmark_data.landmark.getP(LandMarkType.LEFT_EYE_PUPIL).relative.y, 0);

        }
    }
}
      